package com.shop.autoshop.service.imp;

import com.shop.autoshop.mapper.OrderMapper;
import com.shop.autoshop.mapper.ProductMapper;
import com.shop.autoshop.mapper.StockMapper;
import com.shop.autoshop.pojo.Order;
import com.shop.autoshop.pojo.Product;
import com.shop.autoshop.pojo.Query;
import com.shop.autoshop.pojo.Stock;
import com.shop.autoshop.service.OrderService;
import com.shop.autoshop.service.StockService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service("orderService")
public class OrderServiceImp implements OrderService {
    Log log = LogFactory.getLog(getClass());

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public void addOrder(Integer pdId, String addtime, String payId, String orderId, Integer buyNum,Double money, String contact, String password, Integer payMethod,String goods,String gd) {
        orderMapper.addOrder(pdId,addtime,payId,orderId,buyNum,money,contact,password,payMethod,goods,gd);
    }

    @Override
    public Order findByPayId(String payId) {
        return orderMapper.findByPayId(payId);
    }

    @Override
    public void orderAllInspect() {
        List<Order> ods = orderMapper.findInvalidOrder();
        List<Order> invods = new ArrayList<>();
        List<Integer> odids = new ArrayList<>();
        List<Integer> stids = new ArrayList<>();
        Integer idsGdNeedAddNum = 0;
        Date nowDate = new Date();
        for (Order od : ods) {
            Long times = nowDate.getTime()-od.getOdAddtime().getTime();
            if(times > 1000*60*6){
                invods.add(od);
            }
        }


        if(invods.size() == 0){
            log.info("当前没有超时的无效订单！");
        }else{
            for (Order od:invods) {
                odids.add(od.getOdId());
                if(od.getOdGd().equals("") || od.getOdGd() == null){
                    String[] stid = od.getOdGoodId().split(",");
                    for (String id:stid) {
                        stids.add(Integer.valueOf(id));
                    }
                }else{
                    productMapper.addPdGdNum(od.getOdPdId(),od.getOdBuyNum());
                    idsGdNeedAddNum = idsGdNeedAddNum+od.getOdBuyNum();
                }

            }


            if(stids.size() == 0){
                log.info("当前没有超时卡密的无效订单！");
            }else{
                stockMapper.updateStockStates(stids,0);
            }
            orderMapper.delInvalidOrder(odids);

            log.info("清除"+odids.size()+"条超时订单！");
            log.info("释放"+(stids.size()+idsGdNeedAddNum)+"条商品库存！");
        }



    }

    @Override
    public void updateOrderStateAndTsNum(Integer id, Integer state,String tsNum) {
        orderMapper.updateOrderStateAndTsNum(id,state,tsNum);
    }

    @Override
    public List<Query> findAllOrderByQuery(String contact, String password) {
        List<Query> queries = new ArrayList<>();
        List<Order> orders = orderMapper.findOrderByQuery(contact,password);
        if(orders == null){
            return null;
        }
        for (Order od: orders) {
            if(od.getOdGoodId().equals("") || od.getOdGoodId() == null){
                //固定
                Query q = new Query();
                q.setOrderId(od.getOdPayId());
                q.setKh(od.getOdGd());
                q.setKm("");
                q.setPayMethod(od.getOdPayMethod());
                q.setState(od.getOdState());
                queries.add(q);
            }else{
                String goods = od.getOdGoodId();
                String[] ids  =goods.split(",");
                for (String s: ids) {
                    Stock st = stockMapper.findById(Integer.valueOf(s));
                    if(st == null){
                        continue;
                    }
                    Query q = new Query();
                    q.setOrderId(od.getOdPayId());
                    q.setKh(st.getStKh());
                    q.setKm(st.getStMm());
                    q.setPayMethod(od.getOdPayMethod());
                    q.setState(od.getOdState());
                    queries.add(q);
                }
            }
        }
        return queries;
    }

    @Override
    public Map<String, Object> getPageList(int currentPage, int pageSize) {
        //订单列表
        Map<String,Object> map = new HashMap<>();
        int page = (currentPage-1)*pageSize;
        List<Order> pdList = orderMapper.findPageList( page, pageSize);
        map.put("list",pdList);

        //分页信息
        StringBuffer html = new StringBuffer();
        int listCount = orderMapper.odCount();
        int pageCount = listCount/pageSize;
        if(listCount%pageSize != 0){
            pageCount += 1;
        }
        html.append("<li class=\"disabled\"><span>"+currentPage+" / "+pageCount+"</span></li>");
        if(currentPage > 1){
            html.append("<li><a href=\"?page=1\">«</a></li>");
            html.append("<li><a href=\"?page="+(currentPage-1)+"\">‹</a></li>");
        }
        if(pageCount <= 10){
            for(int i = 1;i <= pageCount;i++){
                if(i == currentPage){
                    html.append("<li class=\"active\"><span>"+i+"</span></li>");
                }else{
                    html.append("<li><a href=\"?page="+i+"\">"+i+"</a></li>");
                }
            }
        }else{
            if(currentPage >= 10){
                if(currentPage+5 <= pageCount){
                    for(int i = currentPage-4;i <= currentPage+5;i++){
                        if(i == currentPage){
                            html.append("<li class=\"active\"><span>"+i+"</span></li>");
                        }else{
                            html.append("<li><a href=\"?page="+i+"\">"+i+"</a></li>");
                        }
                    }
                }else{
                    for(int i = currentPage-4;i <= pageCount;i++){
                        if(i == currentPage){
                            html.append("<li class=\"active\"><span>"+i+"</span></li>");
                        }else{
                            html.append("<li><a href=\"?page="+i+"\">"+i+"</a></li>");
                        }
                    }
                }
            }else{
                for(int i = 1;i <= 10;i++){
                    if(i == currentPage){
                        html.append("<li class=\"active\"><span>"+i+"</span></li>");
                    }else{
                        html.append("<li><a href=\"?page="+i+"\">"+i+"</a></li>");
                    }
                }
            }
        }
        if(currentPage < pageCount){
            html.append("<li><a href=\"?page="+(currentPage+1)+"\">›</a></li>");
            html.append("<li><a href=\"?page="+pageCount+"\" >»</a></li>");
        }

        map.put("page",html.toString());


        return map;
    }

    @Override
    public Order findOrderById(Integer id) {
        return orderMapper.findOrderById(id);
    }

    @Override
    public void delOrderByIds(Integer id, String ids) {
        if(id != null){
            orderMapper.delOrderById(id);
        }else if (ids != null && ids != ""){
            String[] array = ids.split(",");
            int[] intArr = new int[array.length];
            for (int i = 0; i < array.length; i++) {
                intArr[i] = Integer.parseInt(array[i]);
            }
            orderMapper.delOrderByIds(intArr);
        }
    }

    @Override
    public Order findOrderByPayIdOrTsNum(String num) {
        return orderMapper.findOrderByPayIdOrTsNum(num);
    }

}
